//
//  BaseTabBarController.m
//  Cycling
//
//  Created by cjg.mini on 2023/3/2.
//

#import "BaseTabBarController.h"
#import "BaseNavigationController.h"
#import "BaseTabBarModel.h"
#import "BaseTabBar.h"
#import "CyclingRootViewController.h"
#import "MineRootViewController.h"
#import "TalkRootViewController.h"
#import "GroupRootViewController.h"
#import "RouteViewController.h"
#import "SaTabBar.h"
#import "AppDelegate.h"
#import "Cycling-Swift.h"
#import "UserRequest.h"
#import "BaseTabBarButton.h"

@interface BaseTabBarController ()<BaseTabBarDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) BaseTabBar *tarbarView;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSMutableArray <BaseTabBarModel *>*modelArray;
@property (nonatomic, strong) MineRootViewController *mineVC;
@property (nonatomic, strong) RouteViewController *routeVC;
@property (nonatomic, strong) CSCyclingRootViewController *cyclingVC;
@property (nonatomic, strong) GroupRootViewController *groupVC;
@property (nonatomic, strong) TalkRootViewController *talkVC;
@property (strong,nonatomic)NSTimer *timer;

@end

@implementation BaseTabBarController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];

}
- (UIScrollView *)scrollView {
    
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.frame = CGRectMake(0, 0, SCREEN_W, SCREEN_H);
        _scrollView.contentSize = CGSizeMake(SCREEN_W*self.modelArray.count, 0);
        _scrollView.delegate = self;
        _scrollView.scrollEnabled = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.backgroundColor = [UIColor colorWithWhite:1 alpha:0];
    }
    return _scrollView;
}

- (BaseTabBar *)tarbarView {
    
    if (!_tarbarView) {
        _tarbarView = [[BaseTabBar alloc] initWithFrame:CGRectMake(0, SCREEN_H-60-SafeAreaBottomHeight, SCREEN_W, 60+SafeAreaBottomHeight)];
        _tarbarView.delegate = self;
        _tarbarView.modelArray = self.modelArray;
    }
    return _tarbarView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [[CycLanguage sharedInstance] configLanguage];

    [self getdata];
    [self setupVCs];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLanguage:) name:CycLanguageNotification object:nil];

}

- (void)changeLanguage:(NSNotification *)sender {
    appDelegate.window.rootViewController = [[BaseNavigationController alloc] initWithRootViewController:[[BaseTabBarController alloc] init]];
    [appDelegate.window makeKeyAndVisible];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CycLanguageNotification object:nil];
}

- (void)getdata {
    NSArray *ary = @[
                     @{
                         @"title":CycLocalizedString(@"Mine", @"我的"),
                         @"defultImage":@"tarbar_mine_no",
                         @"selectedImage":@"tarbar_mine_yes"
                         },
                     @{
                         @"title":CycLocalizedString(@"Route", @"路线"),
                         @"defultImage":@"tarbar_map_no",
                         @"selectedImage":@"tarbar_map_yes"
                         },
                     @{
                         @"title":CycLocalizedString(@"Cycling", @"骑行"),
                         @"defultImage":@"tarbar_cycling",
                         @"selectedImage":@"tarbar_cycling"
                         },
                     @{
                         @"title":CycLocalizedString(@"Ranking", @"排行榜"),
                         @"defultImage":@"tarbar_group_no",
                         @"selectedImage":@"tarbar_group_yes"
                         },
                     @{
                         @"title":CycLocalizedString(@"Service", @"客服"),
                         @"defultImage":@"tarbar_talk_no",
                         @"selectedImage":@"tarbar_talk_yes"
                         }
                     ];
    
    NSMutableArray *arrM = [NSMutableArray array];
    for (NSDictionary *dict in ary) {
        BaseTabBarModel *model = [BaseTabBarModel modelWithDict:dict];
        [arrM addObject:model];
    }
    self.modelArray = [arrM copy];
    
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(loadData) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
        [_timer fire];
    }
    
    [self loadData];
}

- (void)loadData {
    [UserRequest getNoticeNumResult:^(BOOL ret) {
        BaseTabBarButton * TarBarButton = (BaseTabBarButton *)[self.tarbarView viewWithTag:1004];
        TarBarButton.redView.hidden = !ret;
    }];
}

- (void)setupVCs {
    
    [self.view addSubview:self.scrollView];
    [self.view addSubview:self.tarbarView];
    
    //解决scrollview内容视图下移20像素的问题
    if ([[UIDevice currentDevice] systemVersion].floatValue>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.mineVC = ({
        MineRootViewController *vc = [[MineRootViewController alloc] init];
        vc;
    });
    self.routeVC = ({
        RouteViewController *vc = [[RouteViewController alloc] init];
        vc;
    });
//    self.mapVC = ({
//        CSMapRootViewController *vc = [CSMapRootViewController new];
//        vc;
//    });
    self.cyclingVC = ({
        CSCyclingRootViewController *vc = [[CSCyclingRootViewController alloc] init];
        vc;
    });
    self.groupVC = ({
        GroupRootViewController *vc = [[GroupRootViewController alloc] init];
        vc;
    });
    self.talkVC = ({
        TalkRootViewController *vc = [[TalkRootViewController alloc] init];
        vc;
    });

    // 添加子控制器
    [self addChildViewController:self.mineVC];
    [self addChildViewController:self.routeVC];
    [self addChildViewController:self.cyclingVC];
    [self addChildViewController:self.groupVC];
    [self addChildViewController:self.talkVC];

    // 先将第一个子控制的view添加到scrollView上去
    [self.scrollView addSubview:self.mineVC.view];
    self.tarbarView.currentIndex = 0;
}

- (void)setupChildVC:(BaseViewController *)vc title:(NSString *)title image:(NSString *)image selectImage:(NSString *)selectImage{
    
    vc.tabBarItem.title = title;
    vc.tabBarItem.image = [UIImage imageNamed:image];
    vc.tabBarItem.selectedImage = [[UIImage imageNamed:selectImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    BaseNavigationController *navigationVC = [[BaseNavigationController alloc] initWithRootViewController:vc];
    [self addChildViewController:navigationVC];
    
}

#pragma mark ---- tarbar代理
- (void)selectIndex:(int)index {
    [self baseTabBarDidSelectIndex:index];
}
- (void)baseTabBarDidSelectIndex:(NSUInteger)index {
    self.tarbarView.currentIndex = index;
    [self.scrollView setContentOffset:CGPointMake(SCREEN_W*index,0) animated:NO];
    NSLog(@"当前的坐标 －－－－－－－－－－－－－－－－－－－ %lu",(unsigned long)index);
    if (index == 0) {
        self.mineVC = self.childViewControllers[index];
        // 如果已经加载过，就不再加载
        if ([self.mineVC isViewLoaded]) return;
        self.mineVC.view.frame = CGRectMake(SCREEN_W*index, 0, SCREEN_W, SCREEN_H);
        [self.scrollView addSubview:self.mineVC.view];
    }
    if (index == 1) {
        self.routeVC = self.childViewControllers[index];
        // 如果已经加载过，就不再加载
        if ([self.routeVC isViewLoaded]) return;
        self.routeVC.view.frame = CGRectMake(SCREEN_W*index, 0, SCREEN_W, SCREEN_H);
        [self.scrollView addSubview:self.routeVC.view];
    }
    if (index == 2) {
        self.cyclingVC = self.childViewControllers[index];
        // 如果已经加载过，就不再加载
        if ([self.cyclingVC isViewLoaded]) return;
        self.cyclingVC.view.frame = CGRectMake(SCREEN_W*index, 0, SCREEN_W, SCREEN_H);
        [self.scrollView addSubview:self.cyclingVC.view];
    }
    if (index == 3) {
        self.groupVC = self.childViewControllers[index];
        // 如果已经加载过，就不再加载
        if ([self.groupVC isViewLoaded]) return;
        self.groupVC.view.frame = CGRectMake(SCREEN_W*index, 0, SCREEN_W, SCREEN_H);
        [self.scrollView addSubview:self.groupVC.view];
    }
    if (index == 4) {
        self.talkVC = self.childViewControllers[index];
        // 如果已经加载过，就不再加载
        if ([self.talkVC isViewLoaded]) return;
        self.talkVC.view.frame = CGRectMake(SCREEN_W*index, 0, SCREEN_W, SCREEN_H);
        [self.scrollView addSubview:self.talkVC.view];
    }

}

- (void)baseTabBarWillDeselectIndex:(NSUInteger)index
{
    if(index == 2) {
        [self.cyclingVC viewWillDisappear:NO];
    }
}

//获取当前的window
- (UIWindow *)mainWindow
{
    UIApplication *app = [UIApplication sharedApplication];
    return [app keyWindow];
}

- (void)changeToCyclingTabWithRouteJson:(NSArray *)json
{
    self.tarbarView.currentIndex = 2;
    [self.tarbarView.delegate baseTabBarDidSelectIndex:2];
    [self.cyclingVC changeThisPageWithJsonModels:json];
}

- (void)changeToCyclingTabWithRouteJson:(NSArray *)json andLat:(CLLocationDistance)lat lng:(CLLocationDistance)lng
{
    self.tarbarView.currentIndex = 2;
    [self.tarbarView.delegate baseTabBarDidSelectIndex:2];
    [self.cyclingVC changeThisPageWithJsonModels:json lat:lat lng:lng];
}

@end
